package main

import (
	"context"
	"fmt"
	"go_study/grpc-stream/proto"
	"sync"
	"time"

	"google.golang.org/grpc"
)

func main() {
	conn, err := grpc.Dial("127.0.0.1:50052", grpc.WithInsecure())
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	c := proto.NewGreeterClient(conn)
	res, _ := c.GetStream(context.Background(), &proto.StreamReqData{Data: "imooc"})
	// 服务端流模式接收 不断的收取数据
	for {
		a, err := res.Recv() // 如果大家懂socket编程的话就明白了了 都是 send revc 发送和接收
		if err != nil {
			fmt.Println(err)
			break
		}
		fmt.Println(a.Data)
	}

	// 客户端流模式
	pubs, _ := c.PutStream(context.Background())
	i := 0
	for {
		i++
		pubs.Send(&proto.StreamReqData{
			Data: fmt.Sprintf("张三%d", i),
		})
		time.Sleep(time.Second)
		if i > 10 {
			break
		}
	}

	// 双向流模式
	req, _ := c.AllStream(context.Background())
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		defer wg.Done()
		for {
			data, _ := req.Recv()
			fmt.Println("收到客户端消息:" + data.Data)
		}
	}()
	go func() {
		defer wg.Done()
		for {
			req.Send(&proto.StreamReqData{Data: "你好我是客户端"})
			time.Sleep(time.Second)
		}

	}()
	wg.Wait()
}
